package com.yimaxiaoerlang.http;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class NetModel {
    private final String TAG = NetModel.class.getSimpleName();
    private static final NetModel ourInstance = new NetModel();
    private Context context;

   public static NetModel getInstance() {
        return ourInstance;
    }

    protected void init(Context context) {
        this.context = context;
    }

    private NetModel() {

    }

    public <T> void request(Observable<ResultBean<T>> observable, ResultListener<T> resultListener) {
        if (NetUtils.getInstance().getNetWorkState(context) == NetType.NETWORK_NONE) {
            NetException netException = new NetException(NetCode.NOINTERNET, "网络链接失败");
            resultListener.onError(netException);
            return;
        }
        setSubscriber(observable, new Observer<ResultBean<T>>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
                Log.d(TAG, "-----onCompleted-----" + "读取完成");
            }

            @Override
            public void onNext(@NonNull ResultBean<T> tResultBean) {
                Log.d(TAG, "-----onNext-----" + tResultBean.toString());
                //其他具体错误码提前判断
                if (tResultBean.code != 0) {//失败
                    resultListener.onError(new NetException(tResultBean.code, tResultBean.msg));
                    return;
                }
                resultListener.onSuccess(tResultBean.data);

            }

            @Override
            public void onError(@NonNull Throwable e) {
                Log.d(TAG, "-----onError-----error"+e.getMessage());
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "-----onComplete-----");
            }
        });

    }


    //订阅事件
    private <T> void setSubscriber(Observable<ResultBean<T>> observable, Observer<ResultBean<T>> observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

}
